package com.zzsy.carosshopprojects.view.refreshview;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.yatoooon.screenadaptation.ScreenAdapterTools;
import com.zzsy.carosshopprojects.R;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class RefreshViewLayout extends FrameLayout {
    private Context mContext;
    private Unbinder unbinder;
    private boolean mShowNoData;//是否显示没有数据
    private boolean mEnableRefresh;//是否开启下拉刷新
    private boolean mEnableLoadMore;//是否开启加载更多
    private boolean mShowLoading;//是否显示加载框

    @BindView(R.id.recycleView)
    RecyclerView recycleView;
    @BindView(R.id.smartRefresh)
    SmartRefreshLayout smartRefresh;

    private RefreshHelper mRefreshHelper;

    public RefreshViewLayout(Context context) {
        super(context);
    }

    public RefreshViewLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RefreshViewLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.RefreshViewLayout);
        mShowNoData = ta.getBoolean(R.styleable.RefreshViewLayout_showNoData, true);
        mEnableRefresh = ta.getBoolean(R.styleable.RefreshViewLayout_enableRefresh, true);
        mEnableLoadMore = ta.getBoolean(R.styleable.RefreshViewLayout_enableLoadMore, true);
        mShowLoading = ta.getBoolean(R.styleable.RefreshViewLayout_showLoading, true);
        ta.recycle();
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View view = inflater.inflate(R.layout.view_refresh_group, this, false);
        unbinder = ButterKnife.bind(this, view);
        ScreenAdapterTools.getInstance().loadView(view);
        addView(view);
        setRefreshView();
    }

    private void setRefreshView() {
        smartRefresh.setEnableRefresh(mEnableRefresh);
        smartRefresh.setEnableLoadMore(mEnableLoadMore);
        smartRefresh.setOnRefreshListener(refreshLayout -> {
            mRefreshHelper.onRefresh();
        });
        smartRefresh.setOnLoadMoreListener(refreshLayout -> {
            mRefreshHelper.onLoadMore();
        });
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        unbinder.unbind();
    }

    public interface RefreshHelper {
        void onRefresh();

        void onLoadMore();
    }

    public void setRefreshHelper(RefreshHelper refreshHelper) {
        mRefreshHelper = refreshHelper;
    }
}
